package com.lyl.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author lylbell
 * @date 2021-06-23 12:06
 * 字段的自动填充
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 增加的自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictInsertFill(metaObject,"createBy",Long.class,userId);
        this.strictInsertFill(metaObject,"created", Date.class,new Date());
        this.strictInsertFill(metaObject,"lastUpdateTime", Date.class,new Date());
    }



    /**
     * 修改的自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictUpdateFill(metaObject,"modifyBy",Long.class,userId);
        this.strictUpdateFill(metaObject,"lastUpdateTime",Date.class,new Date());
    }

    /**
     * 从安全上下文中获取登录的用户名
     * @return
     */
    private Long getUserId() {
        Long userId = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            String userName = authentication.getPrincipal().toString();
            userId = Long.valueOf(userName);
        }
        return userId;
    }
}
